import { _decorator, Component, Node, Vec3, v3, Quat } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FormationFollowSystem')
export class FormationFollowSystem extends Component {

    @property(Node)
    leader: Node | null = null; // 领导者

    @property([Node])
    followers: Node[] = []; // 跟随者数组

    @property
    formationSpacing: number = 2.0; // 队形间距

    update(deltaTime: number) {
        if (!this.leader || this.followers.length === 0) return;

        // 获取领导者方向
        const leaderForward = this.leader.forward;

        // 计算队形位置
        for (let i = 0; i < this.followers.length; i++) {
            const follower = this.followers[i];
            // 目标位置
            // const targetPosition = this.leader.position.clone().add(offset);
            let targetPosition = this.leader.position;
            let targetNode = this.leader.getChildByName("followerNode" + (i + 1));
            // 创建新向量存储结果
            const result = new Vec3();
            // 使用静态方法相加（不修改原始向量）
            Vec3.add(result, targetPosition, targetNode.position);
            // 平滑移动
            const newPosition = v3();
            Vec3.lerp(newPosition, follower.position, result, 1 * deltaTime);
            follower.setPosition(newPosition);
            // 更新朝向
            follower.forward = leaderForward.clone();
            // this.smoothRotation(leaderForward, 1,follower);
        }
    }

    // 使用四元数球面插值(SLerp)
    private smoothRotation(direction: Vec3, deltaTime: number, followerNode:Node) {
        if (direction.lengthSqr() < 0.01) return;

        // 计算目标朝向
        const targetRotation = Quat.fromViewUp(new Quat(), direction, Vec3.UP);

        // 当前旋转
        const currentRotation = followerNode.rotation;

        // 插值旋转
        const newRotation = new Quat();
        Quat.slerp(newRotation, currentRotation, targetRotation, 10 * deltaTime);

        followerNode.rotation = newRotation;
    }

    // 添加排斥力
    private applySeparationForce(followers: Node[]) {
        const separationRadius = 1.5;
        const separationForce = 5.0;

        for (let i = 0; i < followers.length; i++) {
            for (let j = i + 1; j < followers.length; j++) {
                const followerA = followers[i];
                const followerB = followers[j];
                const distance = Vec3.distance(followerA.position, followerB.position);

                if (distance < separationRadius) {
                    // 计算排斥方向
                    const direction = followerA.position.clone().subtract(followerB.position).normalize();
                    const force = direction.multiplyScalar(separationForce * (1 - distance / separationRadius));

                    // 应用力到两个跟随者
                    followerA.position = followerA.position.clone().add(force.multiplyScalar(0.5));
                    followerB.position = followerB.position.clone().add(force.multiplyScalar(-0.5));
                }
            }
        }
    }
}


